package com.bwton.msx.ccb.ui.auth;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.view.MenuProvider;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.fragment.NavHostFragment;

import com.bwton.msx.ccb.R;
import com.bwton.msx.ccb.databinding.FragmentMenuBinding;
import com.bwton.msx.ccb.service.api.ApiServiceManager;
import com.bwton.msx.ccb.service.api.response.ApiResponse;
import com.bwton.msx.ccb.service.api.response.IgnoreResult;
import com.bwton.msx.ccb.service.auth.AuthService;
import com.bwton.msx.ccb.service.user.User;
import com.bwton.msx.ccb.service.user.UserManager;
import com.bwton.msx.ccb.service.user.UserUiState;
import com.bwton.msx.ccb.utils.RxViewUtils;

import io.reactivex.Notification;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;


public class MenuFragment extends Fragment {
    private CompositeDisposable disposable = new CompositeDisposable();
    private FragmentMenuBinding binding;
    private AuthService authService = new AuthService(ApiServiceManager.getAuth());
    private final static String TAG = MenuFragment.class.getSimpleName();

    @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {

        binding = FragmentMenuBinding.inflate(inflater, container, false);
        return binding.getRoot();

    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        disposable = new CompositeDisposable();
        bindUiEvent();
        Disposable userState = UserManager.getInstance()
                .subscribeUserUIState()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(user -> {
                    displayLoginUiState(user);
                    if (user.isLogin) {
                        bindUiEventWithUser(user.user);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                    }
                });
        disposable.add(userState);
    }

    private void bindUiEvent() {
        binding.btnRegister.setOnClickListener(v -> {
            NavHostFragment.findNavController(this).navigate(R.id.action_menuFragment_to_registerFragment);
        });
        binding.btnLogin.setOnClickListener(v -> {
            NavHostFragment.findNavController(this).navigate(R.id.action_menuFragment_to_loginFragment);
        });
        binding.btnReal.setOnClickListener(v -> {
            NavHostFragment.findNavController(this).navigate(R.id.action_menuFragment_to_realNameFragment);
        });
        binding.btnFaceOpen.setOnClickListener(v -> {
            NavHostFragment.findNavController(this).navigate(R.id.action_menuFragment_to_faceOpenFragment);
        });
        binding.btnLogout.setOnClickListener(v -> {
            UserManager.getInstance().logout();
        });
        binding.btnFaceCancel.setOnClickListener(v -> {
            NavHostFragment.findNavController(this).navigate(R.id.action_menuFragment_to_managerFaceFragment);
        });
        binding.btnLoginPassword.setOnClickListener(v -> {
            NavHostFragment.findNavController(this).navigate(R.id.action_menuFragment_to_login_passwordFragment);
        });


        requireActivity().addMenuProvider(new MenuProvider() {
            @Override
            public void onCreateMenu(@NonNull Menu menu, @NonNull MenuInflater menuInflater) {
                menuInflater.inflate(R.menu.home_menu, menu);
            }

            @Override
            public boolean onMenuItemSelected(@NonNull MenuItem menuItem) {
                if (menuItem.getItemId() == R.id.action_question){
                    NavHostFragment.findNavController(MenuFragment.this).navigate(R.id.action_menuFragment_to_firstFragment);
                    return true;
                }
                return false;
            }
        },getViewLifecycleOwner());
    }
    private void bindUiEventWithUser(User user) {
        binding.btnUpdate.setOnClickListener(v -> {
            authService.updateUserState(user.phone, user.userId, user.unionId);
        });
        binding.btnPassword.setOnClickListener(v -> {
            NavHostFragment.findNavController(this).navigate(R.id.action_menuFragment_to_passwordFragment);
        });
        Disposable unreg = RxViewUtils.throttle(binding.btnUnreg,10)
                .flatMap((Function<View, ObservableSource<ApiResponse<IgnoreResult>>>) view -> authService.unRegUser(user.unionId))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(result->{
                    Toast.makeText(requireContext(),result.errmsg,Toast.LENGTH_SHORT).show();
                    if (result.isSuccess()){
                        UserManager.getInstance().logout();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                    }
                });
        disposable.add(unreg);
    }

    private void displayLoginUiState(UserUiState uiState) {
        if (uiState.isLogin) {
            binding.textDesc.setText(formatUserInfo(uiState.user));
            binding.btnUpdate.setVisibility(View.VISIBLE);
            binding.btnLogout.setVisibility(View.VISIBLE);
            binding.btnRegister.setVisibility(View.GONE);
            binding.btnLogin.setVisibility(View.GONE);
            binding.btnReal.setVisibility(uiState.user.getState().isEnableRealName() ? View.GONE : View.VISIBLE);
            binding.btnFaceOpen.setVisibility(uiState.user.getState().isEnableFace() ? View.GONE : View.VISIBLE);
            binding.btnFaceCancel.setVisibility(uiState.user.getState().isEnableFace() ? View.VISIBLE : View.GONE);
            binding.btnUnreg.setVisibility(View.VISIBLE);
            binding.btnPassword.setVisibility(View.VISIBLE);
            binding.btnLoginPassword.setVisibility(View.GONE);
        } else {
            binding.btnLogout.setVisibility(View.GONE);
            binding.textDesc.setText("无账号登录");
            binding.btnReal.setVisibility(View.GONE);
            binding.btnFaceOpen.setVisibility(View.GONE);
            binding.btnUpdate.setVisibility(View.GONE);
            binding.btnLoginPassword.setVisibility(View.VISIBLE);
            binding.btnRegister.setVisibility(View.VISIBLE);
            binding.btnLogin.setVisibility(View.VISIBLE);
            binding.btnFaceCancel.setVisibility(View.GONE);
            binding.btnUnreg.setVisibility(View.GONE);
            binding.btnPassword.setVisibility(View.GONE);
        }
    }

    private String formatUserInfo(User user) {
        String info = "手机号:" +
                user.phone +
                "\n" +
                "unionId:" +
                user.unionId +
                "\n" +
                "userId:" +
                user.userId +
                "\n" +
                "token:" +
                user.token +
                "\n" +
                "人脸:" +
                (user.state.isEnableFace() ? "已开通" : "未开通") +
                "\n" +
                "实名认证:" +
                (user.state.isEnableRealName() ? "已实名" : "未实名") +
                "\n";
        if (user.state.getFaceState().equals("2")) {
            info += "人脸已冻结";
        }
        return info;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
        disposable.dispose();
        disposable.clear();
    }
}